import {Component, OnInit} from '@angular/core';
import {Music} from './music-player.model';
import {CommonTool} from '../common.tool';
import {FileManagementService} from '../../home/file-management/file-management.service';

@Component({
  selector: 'app-music-player',
  templateUrl: './music-player.component.html',
  styleUrls: ['./music-player.component.scss']
})
export class MusicPlayerComponent implements OnInit {

  public playList: Array<{ id, name, url }> = [];
  public currentMusic: { id, name, url } = {id: '', name: '', url: ''};
  public audio;
  public progress: number; // 进度效果
  public suspend = true;  // 暂停开始
  public mute = false; // 是否静音
  public volumeNum: number; // 音量
  public playType: string; // 播放类型
  public historyList = []; // 历史记录
  public historyIndex = 0; // 历史记录索引
  public history: boolean; // true:正向历史，false：反向历史
  public interval: any;
  public isPlayList = false;

  constructor(public common: CommonTool, public fileManagementService: FileManagementService) {
    this.playType = 'retweet';
    this.progress = 0;
    const body = document.getElementsByTagName('body');
    if (body.length > 0) {
      const player = document.getElementById('xc-music-player');
      if (this.common.notNull(player)) {
        this.audio = player;
        this.progress = this.audio.currentTime;
        this.currentMusic = {id: '0', name: player['name'], url: this.audio.src};
        this.playList.push(this.currentMusic);
        this.suspend = false;
        this.calculationProgress();
      } else {
        this.audio = document.createElement('audio');
        this.audio.id = 'xc-music-player';
        this.audio.className = 'xc-music';
      }
      this.volumeNum = this.audio.volume * 100;
      body[0].appendChild(this.audio);
      this.audio.onended = () => {
        this.playEnd();
      };
    }
  }

  ngOnInit() {
  }

  /**
   * 播放结束
   */
  public playEnd() {
    this.historyIndex++;
    this.progress = 0;
    this.suspend = true;
    const playList = this.playList;
    if (this.playType === 'retweet') {
      // 顺序播放
      for (let i = 0; i < this.playList.length; i++) {
        if (this.playList[i].id === this.currentMusic.id) {
          if (this.common.notNull(this.playList[i + 1])) {
            this.play(this.playList[i + 1].id);
          } else {
            this.play(this.playList[0].id);
          }
          break;
        }
      }
    } else if (this.playType === 'danquxunhuan') {
      // 单曲播放
      this.play(this.currentMusic.id);
    } else if (this.playType === 'random') {
      // 随机播放
      const id = this.getRandomId(playList, this.currentMusic.id);
      this.play(id);
    }
  }

  /**
   * 下一曲
   */
  public nextSong() {
    if (this.common.notNull(this.playList)) {
      if (this.historyIndex === 0) {
        this.history = !this.history;
      }
      if (this.history) {
        if (this.historyIndex === (this.historyList.length - 1)) {
          this.playEnd();
        } else {
          this.historyIndex++;
          this.play(this.historyList[this.historyIndex]);
        }
      } else {
        this.historyIndex--;
        this.play(this.historyList[this.historyIndex]);
      }
    }
  }

  /**
   * 上一曲
   */
  public lastSong() {
    if (this.common.notNull(this.playList)) {
      if (this.historyIndex === 0) {
        this.history = !this.history;
      }
      if (!this.history) {
        this.historyIndex--;
        this.play(this.historyList[this.historyIndex]);
      } else {
        if ((this.historyIndex - 1) === (this.historyList.length - 1)) {
          this.playEnd();
        } else {
          this.historyIndex++;
          this.play(this.historyList[this.historyIndex]);
        }
      }
    }
  }

  /**
   * 获取不包含当前歌曲的id
   */
  public getRandomId(playList, id) {
    const temp = [];
    // 应该在不包括当前的列表中播放
    for (let i = 0; i < playList.length; i++) {
      if (playList[i].id !== id) {
        temp.push(playList[i].id);
      }
    }
    const random = parseInt(String(Math.random() * temp.length));
    return temp[random];
  }

  /**
   * 添加音乐
   */
  public addMusic(music: Music) {
    this.isPlayList = false;
    if (!this.common.notNull(this.playList)) {
      this.playList = [];
    }
    for (const play of  this.playList) {
      if (play.id === music.id) {
        return play.id;
      }
    }
    this.playList.push({
      id: music.id,
      name: music.name,
      url: ''
    });
    return music.id;
  }

  /**
   * 播放
   */
  public play(id?) {
    this.isPlayList = true;
    this.progress = 0;
    if (this.common.notNull(id)) {
      this.fileManagementService.downloadFile(id).subscribe(res => {
        const music = this.getMusic(id, res.url);
        this.audio.src = music.url;
        this.audio.name = music.name;
        this.currentMusic = music;
        this.suspend = false;
        this.audio.play();
        this.calculationProgress();
        this.historyList.push(music.id);
      });
    } else {
      if (this.playList.length > 1) {
        const music = this.playList[0];
        this.audio.src = music.url;
        this.audio.name = music.name;
        this.currentMusic = music;
        this.suspend = false;
        this.audio.play();
        this.calculationProgress();
        this.historyList.push(music.id);
      }
    }
  }


  /**
   * 根据id获取音乐对象
   */
  public getMusic(id, url?) {
    for (const music of this.playList) {
      if (music.id === id) {
        music.url = url;
        return music;
      }
    }
  }

  /**
   * 计算进度
   */
  public calculationProgress() {
    if (this.common.notNull(this.interval)) {
      clearInterval(this.interval);
    }
    this.interval = setInterval(() => {
      const buffer = this.audio.buffered.length;
      if (!this.suspend && buffer > 0) {
        this.progress++;
      }
      if (this.progress >= this.audio.duration) {
        clearInterval(this.interval);
      }
    }, 1000);
  }

  /**
   * 进度
   */
  public progressChange($event) {
    this.audio.currentTime = $event;
  }

  /**
   * 音量调节
   */
  public volumeSize($event) {
    this.audio.volume = $event / 100;
  }

  /**
   * 播放顺序
   */
  public playOrder(playType) {
    if (playType === 'retweet') {
      this.playType = 'random';
    } else if (playType === 'random') {
      this.playType = 'danquxunhuan';
    } else if (playType === 'danquxunhuan') {
      this.playType = 'retweet';
    }
  }

  /**
   * 暂停播放
   */
  public stop(suspend) {
    if (this.common.notNull(this.currentMusic.id)) {
      this.suspend = !suspend;
      if (suspend) {
        this.audio.play();
      } else {
        this.audio.pause();
      }
    }
  }
}
